package com.cci.kangdao.utilTool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;

public class JWTUtil {
    private static Logger log = Logger.getLogger(JWTUtil.class);
    /** 创建JWT */
    public static String createJwt(String secretkey, String issuser, String subject, String userid, long expires)
            throws IllegalArgumentException, UnsupportedEncodingException {

        Algorithm al = Algorithm.HMAC256(secretkey);

        String token = JWT.create().withIssuer(issuser).withSubject(subject).withClaim(userid, 1)
                .withExpiresAt(new Date(System.currentTimeMillis() + expires)).sign(al);

        return token;
    }

    /** 验证jwt */
    public static boolean verifyJwt(String token,String subject ,String userId) {
        try {
            boolean success = false;
            Algorithm algorithm = Algorithm.HMAC256("123456");
            JWTVerifier verifier = JWT.require(algorithm).build();
             DecodedJWT jwt = verifier.verify(token);
            log.info( "验证token：" + jwt.getSubject() + jwt.getExpiresAt() + jwt.getClaims().toString());
             if(null != jwt){
                 Date date = new Date();
                 if(subject.equals(jwt.getSubject()) && jwt.getClaims().containsKey(userId) && jwt.getExpiresAt().getTime() > date.getTime()){
                     success = true;
                 }
             }
             return success;
        } catch (Exception e) {
            e.printStackTrace();
            log.error( e + e.getMessage());
        }
        return false;
    }


    /** 验证jwt */
    public static DecodedJWT decodedJWT(String token, String secretkey) throws UnsupportedEncodingException {
        return JWT.require(Algorithm.HMAC256(secretkey)).build().verify(token);
    }

    private static String emptyString(String s) {
        return s==null? "":s;
    }

    /** 创建JWT */
    public static String jwtToken(String secretkey, String issuser, String audience, String subject,
                                  long expires, Map<String,String> claimMap)
            throws IllegalArgumentException, UnsupportedEncodingException {

        Algorithm al = Algorithm.HMAC256(secretkey);

        JWTCreator.Builder builder = JWT.create();
        builder.withIssuer(emptyString(issuser)).withAudience(emptyString(audience))
                .withSubject(emptyString(subject)).withExpiresAt(new Date(System.currentTimeMillis() + expires));
        for(Map.Entry<String,String> entry: claimMap.entrySet()) {
            builder.withClaim(entry.getKey(), entry.getValue());
        }
        return builder.sign(al);
    }


    public static void main(String[] args) throws IllegalArgumentException, UnsupportedEncodingException, ParseException {


        //String token=JWTUtil.createJwt("123456", "cummins", "STATION", "78822663", 10*365*24*3600*1000L);
        //System.out.println(token);

        //verifyJwt("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiI3NzI4MDIyNSIsInN1YmplY3QiOiJTVEFUSU9OIn0.4HstmcsDdbE1poNxt2lO4Q2cxUA5xQi_UqPxAfL_bgQ","STATION","77280225");
    }
}

